# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import time
import requests
import json
import re

# 参数列表 基金编码code
get_onside_worth_url = 'http://yunhq.sse.com.cn:32041//v1/sh1/snap/{0}?select=prev_close'

def get_onside_worth(code):
    # 发送请求请求头
    headers = dict()
    headers['Accept'] = '*/*'
    headers['Accept-Encoding'] = 'gzip, deflate'
    headers['Accept-Language'] = 'zh-CN, zh;q=0.9'
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36'
    headers['Referer'] = 'http://www.sse.com.cn/'
    headers['Host'] = 'query.sse.com.cn'
    headers['Content-Language'] = 'zh-CN'
    headers['Connection'] = 'keep-alive'

    req = requests.get(get_onside_worth_url.format(code), headers)
    result = json.loads(req.text.encode("utf8"))
    req_time = '{0} {1}'.format(result["date"], result["time"])
    fund_worth = result['snap'][0]
    # print(req_time, fund_worth)
    return (req_time, fund_worth)

def get_outside_worth(code):
    # 发送请求请求头
    headers = dict()
    headers['Accept'] = '*/*'
    headers['Accept-Encoding'] = 'gzip, deflate'
    headers['Accept-Language'] = 'zh-CN, zh;q=0.9'
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36'
    headers['Referer'] = 'http://fund.eastmoney.com/'
    headers['Content-Language'] = 'zh-CN'
    headers['Connection'] = 'keep-alive'

    base_url = 'http://fundgz.1234567.com.cn/js/{0}.js?rt=1623677107085'
    req = requests.get(base_url.format(code), headers)
    result = re.findall(r'jsonpgz\((.*)\);', req.text)[0]
    result = json.loads(result.encode("utf8"))

    # print(result)
    return (result["name"], result['gztime'], result["gsz"])

# 501206 添富创新未来
# 501207 华夏创新未来
# 501205 鹏华创新未来
# 501208 中欧创新未来
# 501203 易方达创新未来
def fund(code):
    # #获取基金中文名
    # china_name = get_china_name(code)
    #通过股票账户获取到的价格
    (req_time, onside_worth) = get_onside_worth(code)
    #通过基金账户获取到的当前净值
    (china_name, gztime, outside_worth) = get_outside_worth(code)
    outside_worth = float(outside_worth)

    discount = (outside_worth - onside_worth) / outside_worth

    nowtime = time.strftime("%Y/%m/%d  %I:%M:%S")

    print("当前时间为北京时间{0},所监控的基金{1},基金编号{2},场内场外折价为{3}".format(nowtime, china_name, code, discount))

# Press the green button in the gutter to run the script.
# 501206 添富创新未来
# 501207 华夏创新未来
# 501205 鹏华创新未来
# 501208 中欧创新未来
# 501203 易方达创新未来
if __name__ == '__main__':
    fund('501203')
    fund('501205')
    fund('501206')
    fund('501207')
    fund('501208')